package com.ahoi.common.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CustomSSOSpringInterceptor implements HandlerInterceptor {

    private static final String NOLOGIN_URL = ".go";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (inContainURL(request, NOLOGIN_URL)) {
            return true;
        }
        return checkLogin(request, response, handler);
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }


    private static boolean inContainURL(HttpServletRequest request, String url) {
        boolean result = false;
        if (url != null && !"".equals(url.trim())) {
            String[] urlArr = url.split(";");
            StringBuffer reqUrl = new StringBuffer(request.getRequestURL());
            for (int i = 0; i < urlArr.length; i++) {
                if (reqUrl.indexOf(urlArr[i]) > 1) {
                    result = true;
                    break;
                }
            }
        }
        return result;
    }

    private boolean checkLogin(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        Token token = SSOHelper.getToken(request);
//        if (token != null) {
//            request.setAttribute(SSOConfig.SSO_TOKEN_ATTR, token);
//        }
//        SSOCommonUser user = SSOHelper.attrTokenUser(request);
//        System.out.println("url:" + request.getRequestURI() + ",user:" + GsonUtils.toJSONString(user));
//                     /*
//                    if (UserType.operator.equals(user.getUser_type())) {
//						// 操作员同一个账号不能登录多个地方
//						String sessionId = StringUtils.defaultString(RedisClientUtil.get("ctoken-" + user.getUser_id()), "");
//						if (!StringUtils.equals(user.getSessionId(), sessionId)) {
//							// 清除cookie
//							request.removeAttribute(ZoomTechUser.ZT_USER_SESSION);
//							request.getSession().invalidate();
//							updateSessionToCookie(request, response);
//							throw createUserTimeoutException();
//						}
//					}
//					*/
//
//        if (user != null) {
//            if (checkCommonUser(user)) {
//                return true;
//            } else {
//                gotoLogin(request, response);
//                return false;
//            }
//        } else {
//            gotoLogin(request, response);
//            return false;
//        }
        return true;
    }


}
